package com.jiancong.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiancong.domain.ResponseResult;
import com.jiancong.domain.dto.RoleQueryCriteria;
import com.jiancong.domain.dto.RoleRequest;
import com.jiancong.domain.dto.RoleUpdateRequest;
import com.jiancong.domain.entity.Role;
import com.jiancong.domain.entity.RoleMenu;
import com.jiancong.domain.vo.ArticleDetailVo;
import com.jiancong.domain.vo.PageVo;
import com.jiancong.mapper.RoleMapper;
import com.jiancong.mapper.RoleMenuMapper;
import com.jiancong.service.RoleService;
import com.jiancong.utils.BeanCopyUtils;
import com.jiancong.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 角色信息表(Role)表服务实现类
 *
 * @author makejava
 * @since 2024-05-08 19:07:30
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<String> selectRoleKeyByUserId(Long id) {
        //判断是否是管理员 如果是返回集合中只需要有admin
        if (id == 1L) {
            List<String> roleKeys = new ArrayList<>();
            roleKeys.add("admin");
            return roleKeys;
        }
        List<String> roles = roleMapper.selectRoleKeyByUserId(id);
        return roles;
    }

    @Override
    public List<Role> listAllRoles() {
        return roleMapper.listAllRoles();

    }

    @Override
    public ResponseResult getRolePageList(RoleQueryCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        //把记录所有数据的集合转化为Page类型
        List<Role> roles = roleMapper.selectRolesByCriteria(criteria);
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        List<Role> roleVos = pageInfo.getList();
        PageVo pageVo = new PageVo(roleVos, pageInfo.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    @Transactional
    public boolean changeRoleStatus(Long id, String status) {
        Role role = new Role();
        role.setId(id);
        role.setStatus(status);
        return roleMapper.updateStatus(role) > 0;
    }

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    @Transactional
    public boolean addRole(RoleRequest roleRequest) {
        // 在这里可以添加额外的逻辑，比如验证角色名称是否已存在等
        // 验证角色名称是否已存在（这通常涉及到查询数据库）
        if (roleMapper.checkRoleNameExists(roleRequest.getRoleName())) {
            throw new IllegalArgumentException("角色名称已存在");
        }
        // 将 DTO 中的数据设置到 Role 实体中
        Role role = BeanCopyUtils.copyBean(roleRequest, Role.class);
        Long userId = SecurityUtils.getUserId();
        role.setCreateBy(userId);
        role.setUpdateBy(userId);
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        int result = roleMapper.insertRole(role);
        if (result > 0) {
            // 插入角色与菜单的关联记录
            for (Long menuId : roleRequest.getMenuIds()) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(role.getId());
                roleMenu.setMenuId(menuId);
                int menuResult = roleMenuMapper.insertRoleMenu(roleMenu);
                if (menuResult <= 0) {
                    // 如果插入失败，则抛出异常，触发回滚
                    throw new RuntimeException("插入角色菜单关联失败");
                }
            }

            return true;
        }
        return false;
    }

    @Override
    public Role getRoleById(Long id) {
        Role role = roleMapper.getRoleById(id);
        if (role == null) {
            new RuntimeException("没有这个角色");
        }
        return role;
    }

    @Override
    @Transactional
    public boolean updateRole(RoleUpdateRequest roleUpdateRequest) {
        Role role = BeanCopyUtils.copyBean(roleUpdateRequest, Role.class);
        int result = roleMapper.updateRole(role);
        if (result > 0) {
            // 删除旧的角色菜单关联
            roleMenuMapper.deleteRoleMenusByRoleId(roleUpdateRequest.getId());
            // 插入新的角色菜单关联
            for (Long menuId : roleUpdateRequest.getMenuIds()) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleUpdateRequest.getId());
                roleMenu.setMenuId(menuId);
                roleMenuMapper.insertRoleMenu(roleMenu);
            }
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean deleteRole(Long id) {
        return roleMapper.deleteRole(id) > 0;
    }


}